//
//  DownloadViewController.m
//  Khmer media
//
//  Created by Rainseylong on 3/7/13.
//  Copyright (c) 2013 imer. All rights reserved.
//

#import "DownloadViewController.h"
#import "AFHTTPRequestOperation.h"


@interface DownloadViewController ()

@end

@implementation DownloadViewController

@synthesize progressView;
@synthesize progrPercen;

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self testDownloadSongs];
    // Do any additional setup after loading the view from its nib.
}

-(void)testDownloadSongs
{
    NSString *urlString=@"http://khmobdroid.com/media/mp3/Bigman/Bigman v22/Bigman v22_4.mp3";
    NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *aUrl = [NSURL URLWithString:escapedUrlString];

    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:aUrl];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename.mp3"];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    
    
    
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"Successfully downloaded file to %@", path);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"Error: %@", error);
    }];
    
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
    {
        float percentDone = ((float)((int)totalBytesRead) / (float)((int)totalBytesExpectedToRead));
        
        self.progressView.progress = percentDone;
        
        
        self.progrPercen.text=[[NSString stringWithFormat:@"%.f",percentDone * 100] stringByAppendingString:@" %"];

    }];

    
    [operation start];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
